namespace Crux.Core.Domains;
/// <summary>
/// EventHandlerFactory
/// </summary>
public class EventHandlerFactory(IEventMappingsFactory eventMappingFactory)
    : IEventHandlerFactory
{
    #region private fields
    /// <summary>
    ///
    /// </summary>
    private readonly IEventMappingsFactory eventMappingFactory = eventMappingFactory
            ?? throw new ArgumentNullException(nameof(eventMappingFactory));
    #endregion  private fields

    #region implements IEventHandlerFactory
    /// <summary>
    /// 
    /// </summary>
    /// <param name="eventDataType"></param>
    /// <param name="serviceProvider"></param>
    /// <returns></returns>
    public IEnumerable<IEventHandler> CreateEventHandlers(
        Type eventDataType,
        IServiceProvider? serviceProvider)
    {
        var runtimeTypeHandles = eventMappingFactory.Get(eventDataType.TypeHandle);

        foreach (var runtimeTypeHandle in runtimeTypeHandles)
        {
            var eventHandlerType = Type.GetTypeFromHandle(runtimeTypeHandle);
            if (eventHandlerType is null) continue;

            IEventHandler? eventHandler = serviceProvider?.GetService(eventHandlerType) as IEventHandler;
            if (null == eventHandler) continue;

            yield return eventHandler;
        }
    }

    #endregion implements IEventHandlerFactory


}